import { ConfigEnv, defineConfig, loadEnv, UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import Unocss from 'unocss/vite'
import PresetWind from '@unocss/preset-wind'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import DefineOptions from 'unplugin-vue-define-options/vite'
import pug from 'vite-plugin-pug'
import extractorPug from '@unocss/extractor-pug'
import { extractorSplit } from '@unocss/core'

// https://vitejs.dev/config/
export default function genViteVueConfig({ command, mode }: ConfigEnv, analyze = false /* 自定义参数 */): UserConfig {
  const envPrefix = ['VITE_', 'VUE_APP_']
  const isDev = mode === 'development'

  let env = loadEnv(mode, process.cwd(), envPrefix)
  env = Object.assign(env, {
    NODE_ENV: isDev ? 'development' : 'production',
    BASE_URL: '/',
    VUE_APP_BUILD_TIME: +new Date(),
  })

  return {
    envPrefix,
    define: {
      'process.env': env,
    },
    server: {
      port: 8080,
      proxy: {
        '/api': {
          target: env.VUE_APP_DEV_API,
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, ''),
        },
      },
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },
    plugins: [
      pug(),
      DefineOptions(),
      AutoImport({
        include: [
          // /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.ts$/,
          /\.vue$/,
          /\.vue\?vue/, // .vue
          /\.md$/, // .md
        ],
        imports: ['vue', 'vue-router'],
        dirs: ['src/store', 'src/request', 'src/hooks'],
        dts: true,
      }),
      Components({
        include: [
          // /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.ts$/,
          /\.vue$/,
          /\.vue\?vue/, // .vue
          /\.md$/, // .md
        ],
        dirs: ['src/layout', 'src/components'],
        resolvers: [
          AntDesignVueResolver({
            resolveIcons: true, // 自动引入 '@ant-design/icons-vue'
          }),
        ],
        dts: true,
        types: [
          {
            from: 'vue-router',
            names: ['RouterLink', 'RouterView'],
          },
        ],
      }),
      Unocss({
        mode: 'global',
        presets: [PresetWind()],
        extractors: [extractorPug(), extractorSplit],
      }),
      vue(), //
    ],
  }
}
